import urllib
# -*- coding: utf-8 -*-

import logging
import urllib2
import re
from pyBookModel.book import Book
from xml.etree import ElementTree as ET
from configobj import ConfigObj

class IsndbClient(object):
    def __init__(self):
        """
        Class constructor
        """
        logging.info("Creating wrapper")
        self.page = 1
        self.val = 10
        self.search_end = False
        config = ConfigObj('conf/pyBook.conf')
        self.key = config['isbndb_key']
        self.books_url = config['isbndb_books_url']
        self.authors_url = config['isbndb_authors_url']
        self.subjects_url = config['isbndb_subjects_url']
        self.categories_url = config['isbndb_categories_url']
        self.publishers_url = config['isbndb_publishers_url']
        self.covers_dir = config['covers_dir']
        self.default_cover = self.covers_dir + config['default_cover']

    def chek_if_more(self, more_results):
        if not more_results:
            self.page = 1
            self.val = 10
            self.search_end = False
        else:
            self.val += 10
            if self.search_end:
                return []

    def search_book_by_isbn(self, isbn, more_results):
        """
        Search a book by title
        """
        self.chek_if_more(more_results)
        logging.info("Search by title: %s" % isbn)
        return self.__search_book_in_page('isbn', isbn)

    def search_books_by_title(self, title, more_results):
        """
        Search a book by title
        """
        self.chek_if_more(more_results)
        logging.info("Search by title: %s" % title)
        return self.__search_book_in_page('title', title)

    def search_books_by_author(self, author, more_results):
        self.chek_if_more(more_results)
        book_list = self.__search_book_in_page('combined', author)
        book_list = self.__filter_by_author(book_list, author)
        return book_list

    def search_books_by_publisher(self, publisher, more_results):
        self.chek_if_more(more_results)
        book_list = self.__search_book_in_page('combined', publisher)
        book_list = self.__filter_by_publisher(book_list, publisher)
        return book_list

    def search_books_by_subject(self, subject, more_results):
        self.chek_if_more(more_results)
        book_list = self.__search_book_in_page('full', subject)
        book_list = self.__filter_by_subject(book_list, subject)
        return book_list

    def __filter_by_author(self, book_list, author):
        book_list_aux = []
        for book in book_list:
            if book.get_authors() is not None:
                if re.match(".*%s.*" % author.lower(),
                    book.get_authors().lower()):
                    book_list_aux.append(book)

        return book_list_aux

    def __filter_by_publisher(self, book_list, publisher):
        book_list_aux = []
        for book in book_list:
            if book.get_publisher() is not None:
                if re.match(".*%s.*" % str(publisher).lower(),
                    book.get_publisher().lower()):
                    book_list_aux.append(book)

        return book_list_aux

    def __filter_by_subject(self, book_list, subject):
        book_list_aux = []
        for book in book_list:
            if book.get_subjects() is not None:
                for sub in book.get_subjects():
                    if re.match(".*%s.*" % str(subject).lower(),
                        sub.lower()):
                        book_list_aux.append(book)

        return book_list_aux

    def __search_book_in_page(self, index, value):
        logging.info("Searching in page: %s" % str(self.page))
        data = {
            'access_key':self.key,
            'index1':index,
            'value1':value,
            'results':'authors,subjects,texts,details',
            'page_number': self.page}

        params = urllib.urlencode(data)
        query = urllib2.urlopen(self.books_url, params)
        data = query.read()
        query.close()

        dom1 = ET.fromstring(data)
        booklist = dom1.find('BookList')

        total_books = booklist.get('total_results')
        logging.info("Total_books: %s" % total_books)

        book_list = []
        for book in booklist:
            # Get book basic data
            book_id = book.get('book_id')
            isbn = book.get('isbn')
            isbn13 = book.get('isbn13')
            title = book.find('Title').text
            title_long = book.find('TitleLong').text
            authors = book.find('AuthorsText').text
            publisher = book.find('PublisherText').text
            summary = book.find('Summary').text
            language = book.find('Details').get('language')
            edition_info = book.find('Details').get('edition_info')
            physical_description = \
                book.find('Details').get('physical_description_text')
            subjects = []
            for subject in book.find('Subjects'):
                subjects.append(subject.text)
            awards = book.find('AwardsText').text
            # Find cover using book seeker
#            if hasattr(self, 'cover_seeker'):
#                pixmap = self.cover_seeker.get_cover(isbn)
#            else:
            pixmap = self.default_cover
            # Create book
            b = Book(book_id, isbn, isbn13, title, title_long,
                authors, publisher, summary, language, edition_info,
                physical_description, subjects, awards, pixmap)

            book_list.append(b)

        if ((self.page*10) < int(total_books) and (self.page < self.val)):
            logging.info("More pages")
            self.page += 1
            return book_list + self.__search_book_in_page(index, value)
        else:
            if (self.page*10) > int(total_books):
                self.search_end = True
            self.page += 1
            logging.info("returning")
            logging.info(len(book_list))
            return book_list
    
